package client

import (
	"awesomeTask/application/resource"
	"awesomeTask/application/variable"
	"awesomeTask/commom/StringHelper"
	event2 "awesomeTask/system/event"
	"awesomeTask/system/registry"
	"net"
	"strings"
)

func BindEvent() {
	/**
	当客户端连接上服务器端报告当前的系统资源
	*/
	event2.Register(variable.ON_CONNECT_SERVER, func(args ...interface{}) {
		EventClientHandlerObj{}.PostNodeStatus()
		EventClientHandlerObj{}.RegisterConfig()
	})

	event2.Register(variable.ON_TRY_KEEPALIVE, func(args ...interface{}) {
		for _, item := range registry.GetDisConnections() {
			switch item["port"].(type) {
			case float64:
				CreateNewClient(item["ipAddress"].(string), int(item["port"].(float64)))
				break
			default:
				CreateNewClient(item["ipAddress"].(string), item["port"].(int))
				break
			}

		}
	})
	//主节点报告当前uid
	event2.Register(variable.ON_POST_SERVER_UNIQUE_ID, func(args ...interface{}) {
		clientInfo := args[0].(map[string]interface{})
		remoteInfo := strings.Split(clientInfo["connection"].(net.Conn).RemoteAddr().String(), ":")
		registry.RecordNode(remoteInfo[0], StringHelper.ParseInt(remoteInfo[1]), clientInfo["uniqueId"].(string))
	})
	//处理主节点分发的资源
	event2.Register(variable.ON_DISTRIBUTE_SOURCE, func(args ...interface{}) {
		sourceInfo := args[0].(map[string]interface{})
		resource.ManagerObj{}.AcceptSource(sourceInfo["content"].(string), sourceInfo["path"].(string))
	})
	event2.Register(variable.ON_BUILD_ENV, func(args ...interface{}) {
		projectName := args[0].(map[string]interface{})["projectName"]
		resource.PythonEnv(projectName.(string))
	})
	event2.Register(variable.ON_SERVER_SEND_STATUS, func(args ...interface{}) {
		info := args[0].(map[string]interface{})
		AddConnection(info["connection"].(net.Conn), info)
	})
}
